package vip.zhenzicheng.nettybasic.splicing.linebase;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;

import java.net.InetSocketAddress;

/**
 * @author zhenzicheng
 * @date 2022-06-24 09:43
 */
public class LineBaseEchoServer {

  public static final int PORT = 9998;

  public static void main(String[] args) throws InterruptedException {
    LineBaseEchoServer lineBaseEchoServer = new LineBaseEchoServer();
    System.out.println("服务器即将启动");
    lineBaseEchoServer.start();
  }

  public void start() throws InterruptedException {
    final LineBaseServerHandler serverHandler = new LineBaseServerHandler();
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();/*服务端启动必须*/
      b.group(group)/*将线程组传入*/
          .channel(NioServerSocketChannel.class)
          .localAddress(new InetSocketAddress(PORT))
          .childHandler(new ChannelInitializerImp());
      ChannelFuture f = b.bind().sync();
      System.out.println("服务器启动完成，等待客户端的连接和数据.....");
      f.channel().closeFuture().sync(); /*阻塞直到服务器的channel关闭*/
    } finally {
      group.shutdownGracefully().sync(); /*优雅关闭线程组*/
    }
  }

  private static class ChannelInitializerImp extends ChannelInitializer<Channel> {

    @Override
    protected void initChannel(Channel ch) throws Exception {
      ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
      ch.pipeline().addLast(new LineBaseServerHandler());
    }
  }

}
